/*
 * AttachmentDataSource.java
 * @author: Jacklau
 * Copyright (c) 2003 BeanSoft Studio
 * Date: Sep 11, 2003
 * @version 1.0
 */

package com.edocbase.desktop.mht;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.activation.DataSource;
import javax.activation.MimetypesFileTypeMap;

/**
 * Referenced classes of package javax.activation: DataSource, FileTypeMap.
 * 
 * AttachmentDataSource implements a DataSource to handle the Attachment class,
 * used by the JavaMail API.
 * 
 * @author BeanSoft
 * @version 2007-6-17
 */

public class AttachmentDataSource implements DataSource {

    private Attachment attachment;
    private MimetypesFileTypeMap map = new MimetypesFileTypeMap();

    /**
     * This is some content type maps.
     */
    private Map normalMap = new HashMap();

    {
	// Initiate normal mime type map
	// Images
	normalMap.put("jpeg", "image/jpeg");
	normalMap.put("jpg", "image/jpeg");
	normalMap.put("gif", "image/gif");
	normalMap.put("png", "image/png");
	normalMap.put("bmp", "image/bmp");
    }

    public AttachmentDataSource(Attachment attachment) {
	this.attachment = attachment;
    }

    public AttachmentDataSource(String fileName) {
	this(new Attachment(fileName));
    }

    /**
     * Returns the content type.
     */
    public String getContentType() {
	// String extension = StringUtil.getExtension(getName());
	// System.err.println("extension=" + extension);
	// String ctype = (String)normalMap.get(extension);
	// if(ctype == null) {
	// return getMimeType(getName());
	// } else {
	// return ctype;
	// }

	return getMimeType(getName());
    }

    public Attachment getAttachment() {
	return attachment;
    }

    public InputStream getInputStream() throws IOException {
	if (getAttachment().getFileData() == null) {
	    getAttachment().setFileData(new byte[0]);
	}

	return new ByteArrayInputStream(getAttachment().getFileData());
    }

    /**
     * Returns the data source's file name.
     */
    public String getName() {
	return getAttachment().getFileName();
    }

    public OutputStream getOutputStream() throws IOException {
	return new java.io.ByteArrayOutputStream();
    }

    private String getMimeType(String fileName) {
	String type = null;
	try {
	    type = map.getContentType(fileName);
	} catch (Exception e) {
	    // TODO: handle exception
	}

	// Fix the null exception
	if (type == null) {
	    type = "application/octet-stream";
	}

	return type;
    }

}